<template>
  <div class="height-full">
    <RoleTabs @on-tab-change="handleTabChange" @on-search-user="handleSearchUser"></RoleTabs>

    <div class="d-flex mt20" style="height: calc(100% - 80px)">
      <div class="user-name--box back-white pad-com height-full">
        <div class="list-caption title-line">角色用户名</div>
        <ul v-if="!userNodata" class="role-username">
          <li
            v-for="(user, i) of userList"
            :key="i"
            :class="activeUserIndex === i && 'active'"
            @click="handleUserClick(user, i)"
            class="role-username--item"
          >
            {{ user.userName || '--' }}
          </li>
        </ul>

        <NoData v-else class="mt80"></NoData>
      </div>

      <div class="authority--box back-white ml14 pad-com height-full">
        <div class="list-caption title-line">功能权限</div>

        <div v-if="!treeDataNodata" class="mt20 ml14">
          <!-- <Checkbox @on-change="handleAllCheck" v-model="authorityModel">全选</Checkbox> -->
          <Tree
            ref="ref_tree"
            class="custom-tree"
            :data="treeData"
            show-checkbox
            @on-check-change="handleTreeCheck"
          ></Tree>
        </div>
        <NoData v-else class="mt80"></NoData>

        <div v-if="!treeDataNodata" class="ml14 text-center">
          <Button @click="resetTreeData">取消</Button>
          <Button class="ml14" type="primary" @click="handleRoleAuthoritySave">保存</Button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ButtonGroupEdit from '@/components/common/ButtonGroupEdit/ButtonGroupEdit.vue'
import RoleTabs from './components/RoleTabs.vue'

// import { mockTreeData } from './service'
import { cloneDeep } from '@/utils/uitls.js'

import mixin from './mixin'
export default {
  name: 'RoleConfig',

  mixins: [mixin],

  components: { ButtonGroupEdit, RoleTabs },

  data() {
    return {
      userList: [],
      activeUserIndex: -1,
      userNodata: false,
      currentRole: {},
      currentFormData: {},
      // treeData: [...mockTreeData()]
      treeData: [],
      treeData_backup: [], // 用来恢复状态
      treeDataNodata: false,
      authorityModel: false,
    }
  },

  watch: {
    treeData(v) {
      this.authorityModel = !v.some((it) => !it.checked)
    },
  },

  methods: {
    handleTabChange(role, data) {
      this.currentRole = role
      this.requestUserList()
      this.requestPowerList()
    },

    handleSearchUser(data) {
      this.currentFormData = Object.freeze(data)
      this.requestUserList()
    },

    requestUserList() {
      this.getSystemUserList({ roleId: this.currentRole.roleId, searchWords: this.currentFormData.searchWords })
      // this.getSystemUserList({ roleId: '', searchWords: this.currentFormData.searchWords })
    },

    requestPowerList() {
      this.getSystemPowerList({ roleId: this.currentRole.roleId })
    },

    handleUserClick(user, i) {
      // this.activeUserIndex = i
    },

    /* 当前已勾选节点的数组、当前项 */
    handleTreeCheck(nodes, currentNode) {
      // console.log('handleTreeCheck', nodes, currentNode)
      // return
      /* 当前节点不选中，当前所有节点有选中 不设置其它节点的状态
        当前节点选中，
       */
      // 当前所有节点
      const currentAllNodes = this.treeData.find(t => t.custom_rootId === currentNode.custom_rootId)
      const allNodesHasChecked = this.nodesIsChecked(currentAllNodes)
      // console.log('allNodesHasChecked', allNodesHasChecked)
      // console.log('currentNode.checked', currentNode.checked)
      if (!currentNode.checked && allNodesHasChecked) {
        return
      }
      this.treeData = this.setTreeDataDisable(cloneDeep(this.treeData), currentNode, currentNode.checked)
    },

    handleAllCheck(isChecked) {
      this.setTreeDataState(this.treeData, isChecked)
    },

    setTreeDataDisable(data, currentNode, state) {
      for (let i = 0, len = data.length; i < len; i++) {
        const it = data[i]
        if (it.custom_rootId === currentNode.custom_rootId) {
          continue
        }
        it.disableCheckbox = state
        if (Array.isArray(it.children) && it.children.length > 0) {
          this.setTreeDataDisable(it.children, currentNode, state)
        }
      }
      return data
    },

    setTreeDataState(data, state) {
      for (let i = 0, len = data.length; i < len; i++) {
        const it = data[i]
        if (Array.isArray(it.children) && it.children.length > 0) {
          this.setTreeDataState(it.children, state)
        }
        if (it.hasOwnProperty('indeterminate')) {
          it.indeterminate = false
        }
        it.checked = state
      }
    },

    handleRoleAuthoritySave() {
      const stateTree = this.$refs['ref_tree'].stateTree
      const PowerIds = this.getCheckNodesIds(stateTree)
      this.getSystemRoleInsertPower({
        roleId: this.currentRole.roleId,
        PowerIds,
      })
    },

    getCheckNodesIds(tree) {
      let ids = ''
      for (let i = 0, len = tree.length; i < len; i++) {
        const it = tree[i]
        if (it.indeterminate || it.checked) {
          ids += it.powerId + ','
          /* 父节点选中子节点再添加 id */
          if (Array.isArray(it.children)) {
            ids += this.getCheckNodesIds(it.children)
          }
        }
      }
      return ids
    },

    resetTreeData() {
      this.treeData = cloneDeep(this.treeData_backup)
    },
  },

  mounted() {
    this.$store.dispatch('system/getSystemRoleList')
  },
}
</script>

<style lang="less" scoped>
.pad-com {
  padding: 18px 12px;
}

.custom-tabs {
  /deep/ .ivu-tabs-nav-container {
    font-size: 16px;
  }
  /deep/ .ivu-tabs-nav .ivu-tabs-tab {
    // margin-right: 20px;
    padding: 0 10px;
  }
  /deep/ .ivu-tabs-bar {
    margin-bottom: 0;
  }
}

.user-name--box {
  flex-shrink: 0;
  width: 400px;

  .role-username {
    width: 93%;
    height: 510px;
    margin: 20px auto;
    overflow: auto;
  }

  .role-username--item {
    height: 50px;
    line-height: 50px;
    text-align: center;
    background-color: #ffffff;
    border: 1px solid #e8e8e8;
    border-bottom: none;

    &.active {
      background-color: #f1f8ff;
    }
  }
  .role-username--item:nth-last-of-type(1) {
    border-bottom: 1px solid #e8e8e8;
  }
}

.authority--box {
  flex-grow: 1;
  overflow: hidden;

  .custom-tree.ivu-tree {
    height: 500px;
    overflow: auto;
    /deep/ .ivu-tree-title {
      color: rgba(0, 0, 0, 0.88);
    }
    /deep/ ul li {
      margin: 14px 0;
    }
  }
}
</style>
